<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ZPituitaryPatientsTag;
use App\Models\ZPituitaryTags;
use App\Models\ZPituitaryVisitReminderAssignLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

/**
 *  随访就诊提醒管理-标签模块
 * Class TagsManageController
 * @package App\Http\Controllers\Api
 */
class TagsManageController extends Controller
{

    /**
     *  获取医院标签 ，支持搜索
     * @param $hospId
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     */
    public function getTagsByHospId($hospId, Request $request)
    {
        $data = $request->all();
        $validate = Validator::make($data, [
            'hospital_id' => 'required',
            'department_id' => 'required'
        ]);
        if ($validate->fails()) {
            return $this->error(42200, "参数异常");
        }
        $searchName = isset($data["name"]) && $data["name"] ? $data["name"] : "";
        $page = isset($data["page"]) && $data["page"] ? $data["page"] : 0;
        $perPage = isset($data["per_page"]) && $data["per_page"] ? $data["per_page"] : 10;

        $res = ZPituitaryTags::getHospTagsArr($data['hospital_id'], $data['department_id'], $searchName, $data['has_num'] ?? '', $page, $perPage);

        return $this->success($res);

    }

    /**
     *  创建标签
     * @param Request $request
     * @return bool|\Illuminate\Contracts\Routing\ResponseFactory|mixed|\Symfony\Component\HttpFoundation\Response
     */
    public function createTag(Request $request)
    {
        $data = $request->all();
        $validate = Validator::make($data, [
            'hospital_id' => 'required',
            'department_id' => 'required',
            'name' => 'required|max:10'
        ]);
        if ($validate->fails()) {
            return $this->error(42200, "参数错误");
        }
        $where = [
            'hospital_id' => $data['hospital_id'],
            'department_id' => $data['department_id'],
            'name' => $data['name'] ?? '',
            'deleted' => 0,
        ];
        $res = ZPituitaryTags::query()->where($where)->first();
        if (!$res) {
            ZPituitaryTags::query()->create($where);
        } else {
            return $this->error(42201, '当前标签已经存在!');
        }

        return $this->success([]);
    }

    /**
     *  修改标签
     * @param $id
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     */
    public function editTagById(Request $request)
    {
        $data = $request->all();
        $validate = Validator::make($data, [
            'id' => 'required',
            'hospital_id' => 'required',
            'department_id' => 'required',
            'name' => 'required|max:10'
        ]);
        if ($validate->fails()) {
            return $this->error(42200, "参数异常");
        }
        $id = $data['id'] ?? 0;
        $res = ZPituitaryTags::query()->where(['id' => $id])->first();
        if ($res) {
            $res->update(['name' => $data['name']]);
        } else {
            return $this->error(42201, '非法操作,操作标签记录不存在!');
        }

        return $this->success([]);
    }

    /**
     *  删除标签
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     */
    public function deleteTag(Request $request)
    {
        $data = $request->all();
        $validate = Validator::make($data, [
            'id' => 'required',
            'hospital_id' => 'required',
            'department_id' => 'required',
        ]);
        if ($validate->fails()) {
            return $this->error(42200, "参数异常");
        }
        $id = $data['id'] ?? 0;

        try {
            DB::beginTransaction();
            ZPituitaryTags::query()->where('id', $id)
                ->where('hospital_id', $data['hospital_id'])
                ->where('department_id', $data['department_id'])
                ->update([
                    'deleted' => 1,
                    'deleted_at' => Carbon::now()->toDateTimeString()
                ]);

            ZPituitaryPatientsTag::query()->where('tag_id', $id)->delete();
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info("删除标签失败" . $id);
            return $this->error(42202, '删除失败');
        }
        return $this->success([]);
    }

    /**
     *  验证标签使用人数
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     */
    public function checkTagCnt(Request $request)
    {
        $data = $request->all();
        $validate = Validator::make($data, [
            'id' => 'required',
            'hospital_id' => 'required',
            'department_id' => 'required'
        ]);
        if ($validate->fails()) {
            return $this->error(42200, "参数异常");
        }
        $id = $data['id'] ?? 0;

        $num = ZPituitaryTags::getUsedNumber($id, $data['hospital_id'], $data['department_id']);

        return $this->success($num);
    }

    /**
     *  获取用户标签
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     */
    public function getUserTags(Request $request)
    {
        $data = $request->all();
        $validate = Validator::make($data, [
            'hospital_id' => 'required',
            'department_id' => 'required',
            'patient_id' => 'required'
        ]);
        if ($validate->fails()) {
            return $this->error(42200, "参数异常");
        }

        $res = ZPituitaryPatientsTag::getUserTags($data['patient_id'], $data['hospital_id'], $data['department_id']);

        return $this->success($res);
    }

    /**
     *  分配标签 删除或者分配
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     */
    public function assignUserTags(Request $request)
    {
        //接口参数 
        $data = $request->all();
        $validate = Validator::make($data, [
            'hospital_id' => 'required',
            'department_id' => 'required',
            'patient_ids' => 'required',
            'add_tag_ids' => 'required_without:del_tag_ids',
            'del_tag_ids' => 'required_without:add_tag_ids',
            'doc_id' => 'required'
        ]);
        if ($validate->fails()) {
            return $this->error(42200, "参数异常");
        }

        $addTags = isset($data["add_tag_ids"]) && $data["add_tag_ids"] ? explode(",", $data['add_tag_ids']) : [];
        $delTags = isset($data["del_tag_ids"]) && $data["del_tag_ids"] ? explode(",", $data['del_tag_ids']) : [];

        $params = [
            'hospital_id' => $data['hospital_id'],
            'department_id' => $data['department_id'],
            'patient_ids' => explode(",", $data['patient_ids']),
            'add_tag_ids' => $addTags,
            'del_tag_ids' => $delTags,
        ];
        $res = ZPituitaryPatientsTag::relateTags($params);

        if (!$res) {
            $this->error(42002, '重新分配失败，请稍后重试');
        }

        ZPituitaryVisitReminderAssignLog::query()->create([
            'doc_id' => $data['doc_id'],
            'hosp_id' => $data['hospital_id'],
            'dept_id' => $data['department_id'],
            'op_type' => 1,
            'data' => json_encode(['params' => $data], 256)
        ]);

        return $this->success([]);
    }

}
